import '../../Utils/FormTemp.scss'

import qs from 'qs'
import { useState } from 'react'
import { useRequest } from 'alova/client'
import { Form, Input, Button, App } from 'antd'

import { GetIndexedDB } from '../../Utils/IndexedDB'
import { Http } from '../../API'

const FormModifyPassword = ({ Off }) => {
    const { notification } = App.useApp();
    const [form] = Form.useForm();
    const [Loading, setLoading] = useState(false)
    const { send } = useRequest(path => Http({ url: 'posVerifyUserNameAndPassword', path }), { immediate: false })
    const onSubmit = async (e) => {
        setLoading(true)
        const [{ uName }] = await GetIndexedDB('userInfo')
        const path = qs.stringify({ UserName: uName, OldPassword: e.oldPaw, Password: e.conPwd })
        send([path]).then(() => {
            notification.success({ key: 'success', message: '成功提醒!', description: '已成功修改密码,下次登录请使用新密码!!' })
            Off()
        })
        setLoading(false)
    }

    return (
        <div className='FormTemplate'>
            <Form
                form={form}
                name="dependencies"
                autoComplete="off"
                layout="vertical"
                className='FormTemp'
                onFinish={onSubmit}
            >
                <Form.Item
                    className='OneFormItem'
                    label="原密码"
                    name="oldPaw"
                    rules={[{ required: true }]}
                >
                    <Input.Password />
                </Form.Item>
                <Form.Item
                    className='OneFormItem'
                    label="新密码"
                    name="newPaw"
                    rules={[{ required: true }]}
                >
                    <Input.Password />
                </Form.Item>
                <Form.Item
                    className='OneFormItem'
                    label="确认新密码"
                    name="conPwd"
                    dependencies={['newPaw']}
                    rules={[
                        { required: true },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (!value || getFieldValue('newPaw') === value) return Promise.resolve()
                                return Promise.reject(new Error('新密码两次不一致!!'));
                            },
                        }),
                    ]}
                >
                    <Input.Password />
                </Form.Item>
                <div className="BtnFormItem">
                    <Button type="primary" htmlType="submit" size='large' loading={Loading}>提交数据</Button>
                </div>
            </Form>
        </div>
    )
}

export default FormModifyPassword